package com.pallass.admin.service.impl;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.pallass.admin.domain.SysResource;
import com.pallass.admin.domain.SysRole;
import com.pallass.admin.repository.SysResourceRepository;
import com.pallass.admin.repository.SysRoleRepository;
import com.pallass.admin.service.SysRoleService;
import com.pallass.common.repository.BaseRepository;
import com.pallass.common.service.BaseServiceImpl;

@Service("roleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole, Integer> implements SysRoleService {

	@Autowired
	private SysRoleRepository sysRoleDAO;

	@Autowired
	private SysResourceRepository resourceDAO;

	public BaseRepository<SysRole, Integer> getBaseDao() {
		return this.sysRoleDAO;
	}

	@Override
	public void grant(Integer roleId, Integer[] resourceIds) {
		SysRole role = sysRoleDAO.findOne(roleId);
		Assert.notNull(role, "角色不存在");

		// TODO 是否只允许超级管理员操作

		SysResource resource;
		Set<SysResource> resources = new HashSet<SysResource>();
		if (resourceIds != null) {
			for (Integer rId : resourceIds) {
				if(rId == null || rId == 0) {
					continue;
				}
				resource = resourceDAO.findOne(rId);
				Assert.notNull(resource, "资源不存在");
				resources.add(resource);
			}
		}

		role.setResources(resources);
		sysRoleDAO.saveAndFlush(role);
	}

}
